package cn.com.checne.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import cn.com.checne.model.domain.LanguageInfo;
import cn.com.checne.model.domain.PostCategory;
import cn.com.checne.model.domain.PostInfo;
import cn.com.checne.model.dto.PostQuery;
import cn.com.checne.util.TimeUtils;


@Repository
public class PostInfoDao {
	protected static final Logger log = Logger.getLogger(PostInfoDao.class);

	/**
	 * create
	 * @param Post
	 * @return
	 */
	public boolean create(PostInfo Post) {
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String createSql = "insert into tbl_post(lg_id_fk,post_cate_id_fk,post_title,post_summary,post_publishdate,post_publishfrom,post_author,post_contenttype,post_content," +
					"post_meta_keyword,post_meta_content,post_isshowindex,post_isshowlist,post_istop,post_firstimage)" +
					" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement pstmt = conn.prepareStatement(createSql);
			int i = 0 ;
			pstmt.setInt(++i,Post.getLanguageId());
			pstmt.setInt(++i,Post.getCateId());
			pstmt.setString(++i, Post.getTitle());
			pstmt.setString(++i,Post.getSummary());
			pstmt.setTimestamp(++i, new java.sql.Timestamp(Post.getPublishDate().getTime()));
			pstmt.setString(++i, Post.getPublishFrom());
			pstmt.setString(++i,Post.getAuthor());
			pstmt.setString(++i,Post.getContent());
			pstmt.setInt(++i, Post.getContentType());

			pstmt.setString(++i,Post.getMetaKeyword());
			pstmt.setString(++i,Post.getMetaContent());
			
			pstmt.setInt(++i,Post.getIsShowIndex());
			pstmt.setInt(++i,Post.getIsShowList());
			pstmt.setInt(++i,Post.getIsTop());
			
			pstmt.setString(++i,Post.getFirstImage());

			pstmt.execute();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result;
	}

	/**
	 * @param Post
	 * @return
	 */
	public boolean update(PostInfo Post) {
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_post set " +
					"lg_id_fk = ?,post_cate_id_fk = ?,post_title = ?,post_summary = ?,post_publishdate =? ,post_publishfrom = ?,post_author =?,post_contenttype=?,post_content=?," +
					"post_meta_keyword =?,post_meta_content=?,post_isshowindex=?,post_isshowlist=?,post_istop=?,post_firstimage=? where post_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			int i = 0 ;
			pstmt.setInt(++i,Post.getLanguageId());
			pstmt.setInt(++i,Post.getCateId());
			pstmt.setString(++i, Post.getTitle());
			pstmt.setString(++i,Post.getSummary());
			pstmt.setTimestamp(++i, new java.sql.Timestamp(Post.getPublishDate().getTime()));
			pstmt.setString(++i, Post.getPublishFrom());
			pstmt.setString(++i,Post.getAuthor());
			pstmt.setString(++i,Post.getContent());
			pstmt.setInt(++i, Post.getContentType());

			pstmt.setString(++i,Post.getMetaKeyword());
			pstmt.setString(++i,Post.getMetaContent());
			
			pstmt.setInt(++i,Post.getIsShowIndex());
			pstmt.setInt(++i,Post.getIsShowList());
			pstmt.setInt(++i,Post.getIsTop());
			
			pstmt.setString(++i,Post.getFirstImage());
			
			pstmt.setInt(++i, Post.getPostId());
			
			pstmt.executeUpdate();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result;
	}

	/**
	 * @param id
	 * @return
	 */
	public boolean delete(int id){
		boolean result;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "delete from tbl_post where post_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			int i = 0 ;
			pstmt.setInt(++i,id);
			log.info("[SQL]" + pstmt.toString());
			pstmt.executeUpdate();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	/**
	 * 
	 * @param PostId
	 * @return
	 */
	public PostInfo getPostById(int PostId) {
		PostInfo Post = new PostInfo();
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_post where post_id = ? ";

			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, PostId);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			List<PostInfo> list = getResult(rs);
			Post = (list != null && list.size() > 0 ) ? list.get(0) : Post ;
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Post;
	}
	/**
	 * 
	 * @param query
	 * @param start
	 * @param num
	 * @return
	 */
	public List<PostInfo> getPostListByCondition(PostQuery query,int start,int num) {
		List<PostInfo> list = new ArrayList<PostInfo>();
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_post where 1=1 " ;
			if(query.getLanguageId() > 0){
				sql += " and lg_id_fk = ? " ;
			}
			if(query.getCateId() > 0){
				sql += " and post_cate_id_fk = ? " ;
			}
			if(query.getIsShowIndex() > -1){
				sql += " and post_isshowindex = ? " ;
			}
			if(query.getIsShowList() > -1){
				sql += " and post_isshowlist = ? " ;
			}
			if(query.getIsTop() > -1){
				sql += " and post_istop = ? " ;
			}
			if(StringUtils.isNotBlank(query.getKw())){
				sql += " and (post_title like ? or post_meta_keyword like ? or post_meta_content like ? or post_content like ? )";
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				sql += " and post_publishdate >= ? ";
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				sql += " and post_publishdate <= ? ";
			}
			sql += "order by post_publishdate desc limit ?,?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			if(query.getLanguageId() > 0){
				pstmt.setInt(++i, query.getLanguageId());
			}
			if(query.getCateId() > 0){
				pstmt.setInt(++i, query.getCateId());
			}
			if(query.getIsShowIndex() > -1){
				pstmt.setInt(++i, query.getIsShowIndex());
			}
			if(query.getIsShowList() > -1){
				pstmt.setInt(++i, query.getIsShowList());
			}
			if(query.getIsTop() > -1){
				pstmt.setInt(++i, query.getIsTop());
			}
			if(StringUtils.isNotBlank(query.getKw())){
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getStartTime()).getTime()));
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getEndTime()).getTime()));
			}
			pstmt.setInt(++i, start);
			pstmt.setInt(++i, num);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			list.addAll(getResult(rs));
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 
	 * @param query
	 * @return
	 */
	public int getPostCountByCondition(PostQuery query) {
		int total = 0 ;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select count(1) as total from tbl_post where 1=1 " ;
			if(query.getLanguageId() > 0){
				sql += " and lg_id_fk = ? " ;
			}
			if(query.getCateId() > 0){
				sql += " and post_cate_id_fk = ? " ;
			}
			if(query.getIsShowIndex() > -1){
				sql += " and post_isshowindex = ? " ;
			}
			if(query.getIsShowList() > -1){
				sql += " and post_isshowlist = ? " ;
			}
			if(query.getIsTop() > -1){
				sql += " and post_istop = ? " ;
			}
			if(StringUtils.isNotBlank(query.getKw())){
				sql += " and (post_title like ? or post_meta_keyword like ? or post_meta_content like ? or post_content like ? )";
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				sql += " and post_publishdate >= ? ";
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				sql += " and post_publishdate <= ? ";
			}
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			if(query.getLanguageId() > 0){
				pstmt.setInt(++i, query.getLanguageId());
			}
			if(query.getCateId() > 0){
				pstmt.setInt(++i, query.getCateId());
			}
			if(query.getIsShowIndex() > -1){
				pstmt.setInt(++i, query.getIsShowIndex());
			}
			if(query.getIsShowList() > -1){
				pstmt.setInt(++i, query.getIsShowList());
			}
			if(query.getIsTop() > -1){
				pstmt.setInt(++i, query.getIsTop());
			}
			if(StringUtils.isNotBlank(query.getKw())){
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
				pstmt.setString(++i, "%" + query.getKw() + "%");
			}
			if(StringUtils.isNotBlank(query.getStartTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getStartTime()).getTime()));
			}
			if(StringUtils.isNotBlank(query.getEndTime())){
				pstmt.setTimestamp(++i, new java.sql.Timestamp(TimeUtils.formatDate(query.getEndTime()).getTime()));
			}
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				total = rs.getInt("total");
			}
			rs.close();
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return total;
	}
	
	
	public boolean setShowIndex(int flag,int...PostIds){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_post set post_isshowindex = ? where post_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			for(int PostId : PostIds){
				int i = 0 ;
				pstmt.setInt(++i,flag);
				pstmt.setInt(++i,PostId);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	
	public boolean setShowList(int flag,int...PostIds){
		boolean result = false;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String updateSql = "update tbl_post set post_isshowlist = ? where post_id = ? ";
			PreparedStatement pstmt = conn.prepareStatement(updateSql);
			for(int PostId : PostIds){
				int i = 0 ;
				pstmt.setInt(++i,flag);
				pstmt.setInt(++i,PostId);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			conn.close();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false ;
		}
		return result ;
	}
	
	public PostInfo isPostExist(int languageId ,int cateId){
		PostInfo Post = null ;
		try {
			Connection conn = DBFactory.getInstance().getConnection();
			String sql = "select * from tbl_post where lg_id_fk = ? and post_cate_id_fk = ?   " ;
			PreparedStatement pstmt = conn.prepareStatement(sql);
			int i = 0 ;
			pstmt.setInt(++i, languageId);
			pstmt.setInt(++i, cateId);
			log.info("[SQL]" + pstmt.toString());
			ResultSet rs = pstmt.executeQuery();
			List<PostInfo> list = getResult(rs);
			Post = (list != null && list.size() > 0 ) ? list.get(0) : null;
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Post ;
	}
	/**
	 * get rseult from resultSet
	 * @param rs
	 * @return
	 */
	public List<PostInfo> getResult(ResultSet rs) {
		List<PostInfo> list = new ArrayList<PostInfo>();
		try {
			PostInfo Post;
			while(rs.next()) {
				Post = new PostInfo();
				Post.setPostId(rs.getInt("post_id"));
				Post.setTitle(rs.getString("post_title"));
				Post.setSummary(rs.getString("post_summary"));
				Post.setPublishDate(rs.getTimestamp("post_publishdate"));
				Post.setPublishFrom(rs.getString("post_publishfrom"));
				Post.setAuthor(rs.getString("post_author"));
				Post.setContentType(rs.getInt("post_contenttype"));
				Post.setContent(rs.getString("post_content"));
				Post.setMetaKeyword(rs.getString("post_meta_keyword"));
				Post.setMetaContent(rs.getString("post_meta_content"));
				Post.setIsShowIndex(rs.getInt("post_isshowindex"));
				Post.setIsShowList(rs.getInt("post_isshowlist"));
				Post.setIsTop(rs.getInt("post_istop"));
				Post.setFirstImage(rs.getString("post_firstimage"));
				
				Post.setLanguageId(rs.getInt("lg_id_fk"));
				LanguageInfo lg = new LanguageInfoDao().getLanguageInfoById(Post.getLanguageId());
				Post.setLanguageInfo(lg);
				
				Post.setCateId(rs.getInt("post_cate_id_fk"));
				PostCategory cate = new PostCategoryDao().getPostCategory(Post.getCateId());
				Post.setPostCategory(cate);
				
				list.add(Post);
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
}